package org.example.common.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * LogAspect
 *
 * @author sym
 * @version 1.0
 * @since 2021-02-10
 */
@Aspect
@Component
public class LogAspect {
    private final static Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(public * org.example.controller.*Controller.*(..))")
    public void controllerMethod() {
    }

    @Before("controllerMethod()")
    public void logRequestInfo(JoinPoint joinPoint) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request;
        if (attributes != null) {
            request = attributes.getRequest();

            StringBuffer requestLog = new StringBuffer();
            requestLog.append("请求信息：")
                    .append("URL = {" + request.getRequestURI() + "},\t")
                    .append("HTTP_METHOD = {" + request.getMethod() + "},\t")
                    .append("IP = {" + request.getRemoteAddr() + "},\t")
                    .append("CLASS_METHOD = {" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + "},\t");

            logger.info(requestLog.toString());
        }
    }

    @AfterReturning(returning = "result", pointcut = "controllerMethod()")
    public void logResultInfo(Object result) {
        logger.info("请求结果：" + result);
    }
}
